const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors());
app.use(express.json());

// 读取内容数据
const getContentData = () => {
  try {
    const dataPath = path.join(__dirname, 'data', 'content.json');
    const rawData = fs.readFileSync(dataPath, 'utf8');
    return JSON.parse(rawData);
  } catch (error) {
    console.error('Error reading content data:', error);
    return {};
  }
};

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: 'Music Platform API Server',
    version: '1.0.0',
    endpoints: [
      'GET /api/content/home',
      'GET /api/content/albums', 
      'GET /api/content/artists'
    ]
  });
});

// 获取首页内容
app.get('/api/content/home', (req, res) => {
  try {
    const contentData = getContentData();
    const homeContent = contentData.home || {};
    
    res.json({
      success: true,
      data: homeContent,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Failed to fetch home content',
      error: error.message
    });
  }
});

// 获取专辑页面内容
app.get('/api/content/albums', (req, res) => {
  try {
    const contentData = getContentData();
    const albumsContent = contentData.albums || {};
    
    res.json({
      success: true,
      data: albumsContent,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Failed to fetch albums content',
      error: error.message
    });
  }
});

// 获取艺术家页面内容
app.get('/api/content/artists', (req, res) => {
  try {
    const contentData = getContentData();
    const artistsContent = contentData.artists || {};
    
    res.json({
      success: true,
      data: artistsContent,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Failed to fetch artists content',
      error: error.message
    });
  }
});

// 获取所有内容 (可选的统一接口)
app.get('/api/content/all', (req, res) => {
  try {
    const contentData = getContentData();
    
    res.json({
      success: true,
      data: contentData,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Failed to fetch all content',
      error: error.message
    });
  }
});

// 404 处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: 'API endpoint not found',
    availableEndpoints: [
      'GET /api/content/home',
      'GET /api/content/albums', 
      'GET /api/content/artists',
      'GET /api/content/all'
    ]
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('Server Error:', error);
  res.status(500).json({
    success: false,
    message: 'Internal server error',
    error: process.env.NODE_ENV === 'development' ? error.message : 'Something went wrong'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 Music API Server is running on http://localhost:${PORT}`);
  console.log(`📋 API Documentation: http://localhost:${PORT}`);
  console.log(`🏠 Home Content: http://localhost:${PORT}/api/content/home`);
  console.log(`💿 Albums Content: http://localhost:${PORT}/api/content/albums`);
  console.log(`🎤 Artists Content: http://localhost:${PORT}/api/content/artists`);
});

module.exports = app;
